package community.hospital.util;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @Author：ydj
 * @Date：2023/1/17 21:30
 */
@Component
public class RedisUtil implements InitializingBean {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private ValueOperations<String, Object> valueOperations;

    public <T> T get(String key, Supplier<T> supplier, long seconds) {
        T value = (T) valueOperations.get(key);
        if (value != null) {
            return value;
        }
        value = supplier.get();
        valueOperations.set(key, value, seconds, TimeUnit.SECONDS);
        return value;
    }

    public <T> T get(String key, Class<T> c) {
        return (T) valueOperations.get(key);

    }

    public Object get(String key) {
        return valueOperations.get(key);

    }

    public void set(String key, Object value, long time, TimeUnit unit) {
        valueOperations.set(key, value, time, unit);
    }

    public void  expire (String key, long ttl, TimeUnit unit){
        redisTemplate.expire(key, ttl, unit);
    }

    public Boolean del(String key) {
        return redisTemplate.delete(key);
    }

    public Long del(List<String> keys) {
        return redisTemplate.delete(keys);
    }

    public Long incr(String key) {
        return valueOperations.increment(key);
    }
    public void expire(String key,Long seconds) {
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }

    public Map<Object, Object> getHash(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
    public void setHash(String key,Object hashKey,Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }
    public void increHash(String key,String hashKey) {
        redisTemplate.opsForHash().increment(key, hashKey, 1);
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        valueOperations = redisTemplate.opsForValue();
    }
}
